var ejs = require('ejs');
var fs = require("fs") ;
var path = require('path');

module.exports = function(app){
	var funcs = {};
	var selectors = {};
	var getInput = function(input){
		if(input.funcConfig) {
			input.funcConfig = JSON.parse(input.funcConfig);

		}
		if(input.selectorConfig) {
			input.selectorConfig = JSON.parse(input.selectorConfig);
			input.selectorName = selectors[input.selectorConfig.id].name;
		}
		return input;
	};
	app.use("/beecode/bcp/selector/", app.static(path.join(__dirname, '../public')));
	app.use("/beecode/bcp/selector/main.html", function(req, res){
		 fs.readFile(path.join(__dirname, '../public/main.ejs'),"utf8",function (error,data){
		    if(error) throw error ;
		    var postData = "";  
		    req.setEncoding("utf8");  
	        req.addListener("data",function(data){  
	            postData  += data;  
	        });  
	        req.addListener("end",function(){ 
	        	var input = JSON.parse(postData);
	        	var renderd = ejs.render(data, getInput(input), {delimiter: '%'});
	        	res.writeHead(200, {
				     'Content-Type': 'text/html' 
				});
	            res.end(renderd);
	        })  
		     
		 });
	});
	app.addReadyListener(function(){
		var comps = global.aminoComponents;
	    for(var i in comps){
	    	if(comps.hasOwnProperty(i)){
	    		var comp = comps[i];
	    		if(comp.selectorCommonFuncID){
	    			funcs[comp.selectorCommonFuncID] = comp;
	    		}
	    		if(comp.selectorConcreteID){
	    			selectors[comp.selectorConcreteID] = comp;
	    		}
	    	}
	    }
	});
}